﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//using Assets.Script.Utils;
//using Unity.Mathematics;

/// <summary>
/// 生成灯光的深度图
/// </summary>
public class CsdnGenDepthMap : MonoBehaviour
{
    
    public Shader depthMapShader;
    [Range(0,1)]
    public float shadowColor = 0.6f;
    [Range(0,0.1f)]
    public float shadowBias = 0.01f;
    public float shadowNormalBias;
    
    [Header("这脚本不需挂在摄像机上")]
    public RenderTexture m_ShadowRT;
    public Camera _lightCamera;//灯光相机
    private List<Vector4> _vList = new List<Vector4>();

    void Start()
    {
        Debug.LogError("ssstart...");
        var obj = new GameObject();

        obj.transform.SetParent(transform,false);
        _lightCamera = obj.AddComponent<Camera>();
        var transform1 = obj.transform;
        transform1.localPosition = Vector3.zero;
        transform1.localScale = Vector3.one;
        transform1.rotation = new Quaternion(0,0,0,0);
        
        //_lightCamera.depthTextureMode = DepthTextureMode.Depth;
        //_lightCamera.clearFlags = CameraClearFlags.SolidColor;
        _lightCamera.backgroundColor = Color.white; //背景色设为白色，表示背景的地方离视点最远，不会受到阴影的影响
        _lightCamera.nearClipPlane = 0.03f;
        _lightCamera.farClipPlane = 30;
        InitCam(_lightCamera);
        _lightCamera.SetReplacementShader(depthMapShader, "RenderType"); //使用替换渲染方式为知道的renderType类型生成深度图
        //RenderTexture depthMap = new RenderTexture(Screen.width, Screen.height, 0);

        //depthMap.format = RenderTextureFormat.AdepthMapRGB32;
        //_lightCamera.targetTexture = ;
        //

        if (_lightCamera.targetTexture == null)
        {
            m_ShadowRT = new RenderTexture(1024, 1024, 24, RenderTextureFormat.RFloat);
            m_ShadowRT.hideFlags = HideFlags.DontSave;
            m_ShadowRT.filterMode = FilterMode.Point;
            _lightCamera.targetTexture = m_ShadowRT;
        }
        
        _lightCamera.SetReplacementShader(depthMapShader, "RenderType");
    }

    void InitCam(Camera cam)
    {
        
        cam.clearFlags = CameraClearFlags.SolidColor;
        cam.backgroundColor = Color.white;
        cam.orthographic = true;
        cam.orthographicSize = 8;
    }

    private void LateUpdate()
    {
     

        Matrix4x4 projectionMatrix = GL.GetGPUProjectionMatrix(_lightCamera.projectionMatrix, false) * _lightCamera.worldToCameraMatrix;
        Shader.SetGlobalTexture("_gShadowMapTexture", m_ShadowRT);
        Shader.SetGlobalFloat("_gShadowBias", shadowBias);
        Shader.SetGlobalFloat("_gShadowNormalBias", shadowNormalBias);
        Shader.SetGlobalMatrix("_gWorldToShadow", projectionMatrix);
        Shader.SetGlobalFloat("_gShadowStrength", shadowColor);
    }
    
    private void OnApplicationQuit()
    {
        _lightCamera.ResetReplacementShader();
    }
}
